/**
 * Copyright 2011 Ivan Hristov
 *
 * hristov.iv [AT] gmail [DOT] com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain a
 * copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */
package com.google.code.johanna.server
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.eclipse.jetty.websocket._
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.CopyOnWriteArraySet
import java.util._
import java.util.concurrent.TimeUnit
import org.eclipse.jetty.websocket.WebSocket.Connection
import scala.collection.JavaConversions._
import java.io.IOException

/**
 *
 * @author Ivan Hristov
 *
 */
class JohannaWebSocketServlet extends WebSocketServlet {

  private val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

  val _members: Set[JohannaSocket] = new CopyOnWriteArraySet[JohannaSocket]();

  override def init() {
    super.init();
    executor.scheduleAtFixedRate(new Runnable() {
      override def run() {
        System.out.println("Running Server Message Sending");
        _members
        for (member: JohannaSocket <- _members) {
          System.out.println("Trying to send to Member!");
          if (member.isOpen()) {
            System.out.println("Sending!");
            try {
              member.sendMessage("Sending a Message to you Guys! " + new Date());
            } catch {
              case e: IOException => e.printStackTrace();
            }
          }
        }
      }
    }, 2, 2, TimeUnit.SECONDS);

  }

  override def doGet(request: HttpServletRequest, response: HttpServletResponse) {

    getServletContext().getNamedDispatcher("default").forward(request,
      response);
  }

  def doWebSocketConnect(request : HttpServletRequest, protocol : String) : WebSocket = {
		new JohannaSocket();
	}
}

class JohannaSocket extends WebSocket.OnTextMessage {
  var _connection : Connection = _

  override def onClose(closeCode: Int, message: String) {
    System.out.print("Connection closed!")
  }

  def sendMessage(data: String) {
    _connection.sendMessage(data);
  }

  def onMessage(data: String) {
    System.out.println("Received: " + data);
  }

  def isOpen(): Boolean = {
    _connection.isOpen();
  }

  def onOpen(connection: Connection) {
    _connection = connection;
    System.out.print("Connection open!")
  }
}